import React from 'react'
import { Button, Form, Input, message } from 'antd';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

export default function Login() {
  const navigate = useNavigate();
  const onFinish = (values) => {
    axios({
      url:`/users?username=${values.username}&password=${values.password}`
    }).then(res =>{
      console.log(res.data)
      if(res.data.length !== 0){
        localStorage.setItem('token', JSON.stringify({
          username: values.username,
          password: values.password
        }))
        navigate('/auth/home')
      }
      else {
        message.warning('登陆失败，请检查用户名或密码是否正确');
      }
    })
  };

  const [form] = Form.useForm();
  return (
    <div className='box' style={{display:'flex', justifyContent:'center', alignItem:'center'}}>
      <Form form={form} name="control-hooks" onFinish={onFinish} style={{marginTop:'50%'}}>
        <Form.Item
          name="username"
          label="用户名"
          style={{borderRadius:'1rem'}}
          rules={[{ required: true, message: '用户名不能为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: '密码不能为空' }]}
        >
          <Input type='password'/>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{marginLeft:'2rem'}}>
            登录
          </Button>
          <Button htmlType="button" onClick={()=>navigate('/register')} style={{marginLeft:'2rem'}}>
            注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
